import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:smart_ai_dart/utils/log_utils.dart';

class EditProfileController extends GetxController {
  final nicknameController = TextEditingController();
  final emailController = TextEditingController();
  final phoneController = TextEditingController();

  final avatarUrl = ''.obs;

  @override
  void onInit() {
    super.onInit();
    _loadUserProfile();
  }

  void _loadUserProfile() {
    // TODO: 从本地存储或网络获取用户信息
    avatarUrl.value = 'https://example.com/avatar.png';
    nicknameController.text = '张三';
    emailController.text = 'zhangsan@example.com';
    phoneController.text = '13800138000';
  }

  void changeAvatar() async {
    final picker = ImagePicker();
    final result = await Get.bottomSheet(
      Container(
        color: Colors.white,
        child: Wrap(
          children: [
            ListTile(
              leading: const Icon(Icons.camera_alt),
              title: Text('take_photo'.tr),
              onTap: () async {
                Get.back();
                final pickedFile =
                    await picker.pickImage(source: ImageSource.camera);
                if (pickedFile != null) {
                  _uploadAvatar(pickedFile.path);
                }
              },
            ),
            ListTile(
              leading: const Icon(Icons.photo_library),
              title: Text('choose_from_album'.tr),
              onTap: () async {
                Get.back();
                final pickedFile =
                    await picker.pickImage(source: ImageSource.gallery);
                if (pickedFile != null) {
                  _uploadAvatar(pickedFile.path);
                }
              },
            ),
          ],
        ),
      ),
    );
  }

  void _uploadAvatar(String filePath) {
    // TODO: 实现头像上传逻辑
    LogUtils.shared.d('上传头像：$filePath');
    avatarUrl.value = filePath;
  }

  void saveProfile() {
    // 验证输入
    if (_validateInputs()) {
      // TODO: 实现保存用户信息的网络请求
      Get.snackbar(
        'success'.tr,
        'profile_updated'.tr,
        snackPosition: SnackPosition.BOTTOM,
      );
      Get.back(); // 返回上一页
    }
  }

  bool _validateInputs() {
    final nickname = nicknameController.text.trim();
    final email = emailController.text.trim();
    final phone = phoneController.text.trim();

    if (nickname.isEmpty) {
      Get.snackbar('error'.tr, 'nickname_required'.tr);
      return false;
    }

    if (email.isEmpty || !GetUtils.isEmail(email)) {
      Get.snackbar('error'.tr, 'invalid_email'.tr);
      return false;
    }

    if (phone.isEmpty || !GetUtils.isPhoneNumber(phone)) {
      Get.snackbar('error'.tr, 'invalid_phone'.tr);
      return false;
    }

    return true;
  }

  @override
  void onClose() {
    nicknameController.dispose();
    emailController.dispose();
    phoneController.dispose();
    super.onClose();
  }
}
